package models

import (
	"encoding/gob"
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// Contacts 联系人
type Contacts struct {
	ContactId    int       `json:"contactId" orm:"column(contact_ID)"`
	ContactName  string    `json:"contactName" orm:"column(contact_name)"`
	PhoneNumber  string    `json:"phoneNumber" orm:"column(phone_number)"`
	Email        string    `json:"email" orm:"column(email)"`
	EnterTime    time.Time `json:"enterTime" orm:"column(enter_time)"`
	HeadPhotoURL string    `json:"headPhotoURL" orm:"column(head_photo_url)"`
}

func init() {
	gob.Register(Contacts{})
	orm.RegisterModel(new(Contacts))
}

// AddContact 添加联系人
func AddContact(contact Contacts) int64 {
	o := orm.NewOrm()
	insert, err := o.Insert(contact)
	if err != nil {
		return -1
	}
	return insert
}

// SelectByPhoneNumber 按电话查询
func SelectByPhoneNumber(phone string) (Contacts, error) {
	contact := Contacts{PhoneNumber: phone}
	o := orm.NewOrm()
	err := o.Read(&contact, "PhoneNumber")
	if err != nil {
		return Contacts{}, err
	}
	if errors.Is(err, orm.ErrNoRows) {
		return Contacts{}, err
	} else if errors.Is(err, orm.ErrMissPK) {
		return Contacts{}, err
	}
	return contact, nil
}

// SelectByContactId 按ID查询
func SelectByContactId(contactID int) (Contacts, error) {
	contact := Contacts{ContactId: contactID}
	o := orm.NewOrm()
	err := o.Read(&contact, "ContactID")
	if err != nil {
		return Contacts{}, err
	}
	if errors.Is(err, orm.ErrNoRows) {
		return Contacts{}, err
	} else if errors.Is(err, orm.ErrMissPK) {
		return Contacts{}, err
	}
	return contact, nil
}
